<script>
/**
 * 在默认标签中打开路由(在属于同一个上级节点菜单标签中中打开下级路由)
 */
import BaseMultiTab from './BaseMultiTab.vue'
export default {
  extends: BaseMultiTab,
  methods: {
    back (n) {
      const parent = this.getParent()
      if (n >= 0 || !parent) {
        window.history.prototype.go(n)
        return
      }
      const stack = parent.meta.stack
      if (stack.length < 2) {
        const path = parent.fullPath || parent.path
        if (path != this.$route.fullPath && path != this.$route.path) {
          this.$router.push({ path, replace: true })
        } else {
          this.remove(this.getTabKey(parent))
        }
        return
      }
      stack.pop()
      this.$router.push({ ...stack.pop(), replace: true })
      this.$forceUpdate()
    },
    handleRouteChange () {
      let parent = this.getParent(),
        current = this.pages.find(p => p.name == parent?.name || p.name == this.$route.name)
      this.$route.meta.type != '3' && (parent = null)
      if (parent) {
        this.activeKey = parent.name
        this.pushRouteStack(parent)
      } else {
        this.activeKey = this.$route.name
      }
      if (!current) {
        this.pages.push(parent || this.$route)
        this.$emit('tabChange', (parent || this.$route).name, parent || this.$route)
      }
      // 更新路由保持
      this.$store.updateKeepAlive(this.pages)
      this.$forceUpdate()
    },
    getTabTitle (page) {
      let title = page.meta.title
      const last = [...page.meta?.stack || []].pop()
      if (last) {
        title = `${title}-${last.meta.title}`
      } else if (page.meta.type == '3') {
        const parent = this.getParent(page)
        if (parent) {
          title = `${parent.meta.title}-${title}`
        }
      }
      return title
    },
    getTabKey (page) {
      return page.name
    },
    pushRouteStack (parent) {
      parent.meta.stack = parent.meta.stack || []
      const stack = parent.meta.stack
      if (stack.find(r => r.name == this.$route.name)) {
        return
      }
      if (this.$route.path == parent.path || this.$route.path == parent.redirect) {
        stack.splice(0, 0, this.$route)
        stack.length = 1
        return
      }
      stack.push(this.$route)
    }
  }
}
</script>